﻿using AutoMapper;
using JunionRobotTaskManager.Dtos;
using JunionRobotTaskManager.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace JunionRobotTaskManager.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SystemInfoController : ControllerBase
    {
        private readonly IOptionsMonitor<SystemInfo> _options;
        private readonly ILogger<SystemInfoController> _logger;
        private readonly IMapper _mapper;
        public SystemInfoController(ILogger<SystemInfoController> logger,
            IOptionsMonitor<SystemInfo> options,
            IMapper mapper)
        {
            _options = options;
            _logger = logger;
            _mapper = mapper;
        }



        /// <summary>
        /// 获取参数
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<ApiResult> GetSystemInfo()
        {

            try
            {
                var dto = _mapper.Map<SystemInfoDto>(_options.CurrentValue);
                return ApiResultHelper.Success(dto);
            }
            catch (Exception e)
            {
                return ApiResultHelper.Error("查找系统信息错误" + e.Message);
            }

        }


        /// <summary>
        /// 更新参数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<ApiResult> UpdateSettingInfo(SystemInfoDto dto)
        {

            try
            {
                var systemInfo = _mapper.Map<SystemInfo>(dto);
                var filePath = System.IO.Path.Combine(Environment.CurrentDirectory, "appsettings.json");
                JObject jsonObject;
                using (StreamReader file = new StreamReader(filePath))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                    jsonObject["SystemSetting"] = JObject.Parse(JsonConvert.SerializeObject(systemInfo));
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
                {
                    jsonObject.WriteTo(jsonwriter);
                }
                return ApiResultHelper.Success(_options.CurrentValue);

            }
            catch (Exception e)
            {
                return ApiResultHelper.Error("更新出错" + e.Message);
            }

        }
    }
}
